# -*- coding: utf-8 -*-

import logging
import json
import hashlib
from django.utils.encoding import smart_unicode
from common.sms import db as sms_db
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError
from django.views.decorators.http import require_POST, require_GET
from async.async_job import handler_sms_order

_LOGGER = logging.getLogger('hydra')

_KEY = '6df03bc8d7d04348a61f8042b8d45312'


def generate_sign(d, key):
    s = ''
    for k in sorted(d.keys()):
        s += '%s=%s&' % (k, d[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _verify_sign(d):
    sign = d.pop('sign')
    gen_sign = generate_sign(d, _KEY)
    if sign != gen_sign:
        raise ParamError('sign error')


@require_GET
@response_wrapper
def get_last_out_sms_id(req):
    query_dct = req.GET.dict()
    _LOGGER.info('sms_verify_warning: %s', query_dct)
    _verify_sign(query_dct)
    id = sms_db.get_last_sms_out_id(query_dct['phone'])
    return {'result': 'ok', 'id': id}


@require_POST
@response_wrapper
def notify_sms(req):
    _LOGGER.info('upload_sms_record: %s', req.body)
    if req.ip not in ['127.0.0.1', '103.230.240.50', '103.230.242.129']:
        raise ParamError('ip %s not in white list' % req.ip)
    param_dct = json.loads(smart_unicode(req.body))
    _verify_sign(param_dct)
    sms_id = sms_db.insert_sms(param_dct)
    _LOGGER.info('notify_sms sms_id: %s', sms_id)
    if sms_id:
        handler_sms_order.delay(sms_id)
    return {'result': 'ok'}
